# -*- coding: utf-8 -*-

import os, re
import urllib
from django.utils import simplejson
from django.http import HttpResponse
#from django.core.urlresolvers import reverse

from seblog.web.render import render_to_response
from seblog.settings import PROJECT_PATH, URL_PREFIX
from seblog.common_logic.utility.util import ensure_unicode
from seblog.common_logic.utility.peutil import is_pe
from seblog.common_logic.utility.const import FileType, FileTypeName
from seblog.common_logic.utility.fileutil import get_filetype

def get_line_index_str(line_index):
    if line_index<10:
        line_index_str = '%s&nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;'
    elif line_index<100:
        line_index_str = '%s&nbsp;&nbsp;|&nbsp;'
    else:
        line_index_str = '%s|&nbsp;'
    return line_index_str %str(line_index)

def index(request):
    template = 'demoapp/file_browser/file_browser.html'
    ProjectPath = os.path.split(PROJECT_PATH)[0]#
    r_dic = {'base':{'path':urllib.quote(ProjectPath),'request_url':'%s/demo/filebrowser/get/' %URL_PREFIX, 'getcontext_url':'%s/demo/filebrowser/showcontext/' %URL_PREFIX,}}
#    r_dic = {'base':{'path':urllib.quote(ProjectPath),'request_url':reverse('file-browser-dirlist') , 'getcontext_url':reverse('file-browser-showcontext'),}}
    return render_to_response(template, r_dic, request)

def dirlist(request):
    r = ['<ul class="jqueryFileTree treeview" style="display: none;">']
    try:
        ProjectPath = os.path.split(PROJECT_PATH)[0]
        r = ['<ul class="jqueryFileTree treeview" style="display: none;">']
        d = urllib.unquote(request.POST.get('dir', ProjectPath))
        for f in os.listdir(d):
            ff = os.path.join(d, f)
            if os.path.isdir(ff):
                r.append('<li class="directory collapsed"><a href="#" rel="%s/">%s</a></li>' % (ff,f))
            else:
                e = os.path.splitext(f)[1][1:] # get .ext and remove dot
                r.append('<li class="file ext_%s"><a href="#" rel="%s">%s</a></li>' % (e,ff,f))
#                r.append('<li class="expanded"><a href="#" rel="%s"><div class="ext_%s">%s</div></a></li>' % (ff,e,f))
        r.append('</ul>')
    except Exception,e:
        r.append('Could not load directory: %s' % str(e))
    r.append('</ul>')
    return HttpResponse(''.join(r))

def showcontext(request):
    req = request.REQUEST
    context = ''
    file_type = ''
    line_index = 1
    file_path = req.get("file_path", None)
    if not file_path or not os.path.exists(file_path) or os.path.isdir(file_path):
        context = 'path not found or it is dir path'
    else:
        ret, file_type = is_pe(file_path)
        if ret:
            file_type_name = FileTypeName[file_type]
            context = "this file is a pe file(%s),so can't be read." %file_type_name
        else:
            file_type = get_filetype(file_path)
            if file_type >= FileType.JPG and file_type <= FileType.ICO:
                file_type = 'image_type'
                try:
                    path_end = file_path[file_path.index('media')-1:]
                    rawstr = r"\b%s\b" %'media'
                    img_path = re.subn(rawstr, 'site_media', path_end, 1)[0]
                    context = img_path
                except:
                    context = "this img can't be see, it isn't in site_media dir path"
            else:
                data_file = open(file_path, 'r')
                try:
                    for line in data_file:
#                        line = line.decode('gb2312')
                        try:
                            line = ensure_unicode(line)
                            line_index_str = get_line_index_str(line_index)
                            context += line_index_str + line + '<br/>'
                            line_index += 1
                        except Exception,e:
                            context = str(e)
                            break
                finally:
                    data_file.close()
    
    r_dic = {'data' : context, 'file_type':file_type}
    r_dic['success'] = True
    result = simplejson.dumps(r_dic,ensure_ascii=False)
    return HttpResponse(result)

def download(request):#大文件会耗死内存滴
    req = request.REQUEST
    file_path = req.get("file_path", None)
    if file_path and os.path.exists(file_path):
        file_name = os.path.split(file_path)[1]
        f = open(file_path)
        data = f.read()
        f.close()

        response = HttpResponse(data,mimetype='application/octet-stream')
        response['Content-Disposition'] = 'attachment; filename=%s' % file_name
        return response
    else:
        return HttpResponse('get file path error')

if __name__ == "__main__":
    print get_line_index_str(1200)
        
        
